﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1.ConfigCmd
{
    class configCommand
    {
        private static configCommand _instance;
        private Crc16 crc16 = new Crc16();

        public struct IP
        {
            public string ip1;
            public string ip2;
            public string ip3;
            public string ip4;
            public string port;
        };

        public static IP ip;

        public static configCommand instance
        {
            get
            {
                if (_instance == null)
                    _instance = new configCommand();
                return _instance;
            }
        }

        private string getMobileNum(string MonitorDev_Id)
        {
            try
            {
                var queryNum =
                from num in Monitor_DB.instance.db.tb_monitor_device
                where num.ID == Convert.ToInt32(MonitorDev_Id)
                join mobile in Monitor_DB.instance.db.tb_mobileNum on num.Mobile_num_Id equals mobile.ID
                select mobile;


                return queryNum.First().Mobile_num;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        private string getMonitorDeviceId(string MonitorDev_Id)
        {
            try
            {
                var queryNum =
                from num in Monitor_DB.instance.db.tb_monitor_device
                where num.ID == Convert.ToInt32(MonitorDev_Id)
                select num;

                return queryNum.First().Name;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        private string getDateTime()
        {
            try
            {
                string month = "";
                if (DateTime.Now.Month < 10)
                {
                    month = "0" + DateTime.Now.Month.ToString();
                }
                else
                {
                    month = DateTime.Now.Month.ToString();
                }

                string day = "";
                if (DateTime.Now.Day < 10)
                {
                    day = "0" + DateTime.Now.Day.ToString();
                }
                else
                {
                    day = DateTime.Now.Day.ToString();
                }

                string hour = "";
                if (DateTime.Now.Hour < 10)
                {
                    hour = "0" + DateTime.Now.Hour.ToString();
                }
                else
                {
                    hour = DateTime.Now.Hour.ToString();
                }

                string min = "";
                if (DateTime.Now.Minute < 10)
                {
                    min = "0" + DateTime.Now.Minute.ToString();
                }
                else
                {
                    min = DateTime.Now.Minute.ToString();
                }

                string sec = "";
                if (DateTime.Now.Second < 10)
                {
                    sec = "0" + DateTime.Now.Second.ToString();
                }
                else
                {
                    sec = DateTime.Now.Second.ToString();
                }

                string time = DateTime.Now.Year.ToString() + month + day + hour + min + sec;

                return time;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }

        // 01：门控制
        public bool RequestDoorCtrl(string deviceId, string MonitorDev_Id, bool frontDoor, bool backDoor)
        {
            try
            {
                string mobileNumOri = getMobileNum(MonitorDev_Id);

                if (mobileNumOri.Length != 11)
                {
                    MessageBox.Show("手机号不正确！号码：%s", mobileNumOri.Length.ToString());
                    return false;
                }

                // Add "86" for sms
                string mobileNum = "86" + mobileNumOri;


                SMS_Send sms = new SMS_Send();
                sms.DestID = mobileNum;
                sms.Disposed = 0;
                sms.DisposedTime = null;
                sms.InsertTime = DateTime.Now;
                sms.Acked = 0;

                string Device_ID = getMonitorDeviceId(MonitorDev_Id);
                sms.Device_ID = Device_ID;
                sms.Command = "01";

                ///// MsgContent
                // Time
                string time = getDateTime();

                // Front Door
                string front = "";
                if (frontDoor)
                {
                    front = "01";
                }
                else
                {
                    front = "00";
                }

                // Back Door
                string back = "";
                if (backDoor)
                {
                    back = "01";
                }
                else
                {
                    back = "00";
                }

                string content = Device_ID + "01" + front + back + time;

                // MsgContent
                sms.Msgcontent = content.Length.ToString() + content ;

                ///// MsgContent

                // MsgContent
                string hexEffLength = Convert.ToString(content.Length, 16).ToUpper();
                if (hexEffLength.Length < 2)
                {

                    sms.Msgcontent = "0" + hexEffLength + content;
                }
                else
                {
                    sms.Msgcontent = hexEffLength + content;
                }

                //// CRC16

                //// Generate CRC16 and convert to 16进制
                //string crcHex = crc16.GetChecksumHex(Encoding.Default.GetBytes(sms.Msgcontent));

                sms.Msglen = sms.Msgcontent.Length;


                Monitor_DB.instance.db.SMS_Send.InsertOnSubmit(sms);
                Monitor_DB.instance.db.SubmitChanges(ConflictMode.FailOnFirstConflict);

                return true;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }

        // 02：请求发送数据
        public bool RequestDevData(string deviceId, string MonitorDev_Id)
        {
            try
            {
                string mobileNumOri = getMobileNum(MonitorDev_Id);

                if (mobileNumOri.Length != 11)
                {
                    MessageBox.Show("手机号不正确！号码：%s", mobileNumOri.Length.ToString());
                    return false;
                }

                // Add "86" for sms
                string mobileNum = "86" + mobileNumOri;


                SMS_Send sms = new SMS_Send();
                sms.DestID = mobileNum;
                sms.Disposed = 0;
                sms.DisposedTime = null;
                sms.InsertTime = DateTime.Now;
                sms.Acked = 0;

                string Device_ID = getMonitorDeviceId(MonitorDev_Id);
                sms.Device_ID = Device_ID;
                sms.Command = "02";

                ///// MsgContent

                // Time
                string time = getDateTime();

                string content = Device_ID + "02" + time;

                // MsgContent
                sms.Msgcontent = content.Length.ToString() + content;

                // MsgLength
                sms.Msglen = sms.Msgcontent.Length;

                ///// MsgContent

                // MsgContent
                string hexEffLength = Convert.ToString(content.Length, 16).ToUpper();
                if (hexEffLength.Length < 2)
                {
                    sms.Msgcontent = "0" + hexEffLength + content;
                }
                else
                {
                    sms.Msgcontent = hexEffLength + content;
                }

                //// CRC16

                //// Generate CRC16 and convert to 16进制
                //crcHex = crc16.GetChecksumHex(System.BitConverter.GetBytes(1021));

                sms.Msglen = sms.Msgcontent.Length;

                Monitor_DB.instance.db.SMS_Send.InsertOnSubmit(sms);
                Monitor_DB.instance.db.SubmitChanges(ConflictMode.FailOnFirstConflict);

                return true;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }

        // 03：门卡授权
        public bool DoorAuthCard(string deviceId, string MonitorDev_Id, Array cardId, int cardCount)
        {
            try
            {
                for (int i = 0; i < cardCount; )
                {
                    string mobileNumOri = getMobileNum(MonitorDev_Id);

                    if (mobileNumOri.Length != 11)
                    {
                        MessageBox.Show("手机号不正确！号码：%s", mobileNumOri.Length.ToString());
                        return false;
                    }

                    // Add "86" for sms
                    string mobileNum = "86" + mobileNumOri;


                    SMS_Send sms = new SMS_Send();
                    sms.DestID = mobileNum;
                    sms.Disposed = 0;
                    sms.DisposedTime = null;
                    sms.InsertTime = DateTime.Now;
                    sms.Acked = 0;

                    string Device_ID = getMonitorDeviceId(MonitorDev_Id);
                    sms.Device_ID = Device_ID;
                    sms.Command = "03";

                    ///// MsgContent

                    // 卡号
                    string card = "";
                    for (int p = i; p < cardCount; ++p)
                    {
                        // 5组卡号发一次
                        if (p > i + 4)
                            break;

                        // 卡号转为16进制
                        string temp = Convert.ToString(Convert.ToInt64(cardId.GetValue(p)), 16).ToUpper();

                        // 不够8位字符的，前面补0
                        if (temp.Length < 8)
                        {
                            int gap = 8 - temp.Length;
                            string zero = "";
                            for(int g = 0;g<gap; ++g)
                            {
                                zero += "0";
                            }

                            temp = zero + temp;
                        }

                        card += temp;    
                    }

                    string content = Device_ID + "03" + card;

                    // MsgContent
                    string hexEffLength = Convert.ToString(content.Length, 16).ToUpper();
                    if (hexEffLength.Length < 2)
                    {

                        sms.Msgcontent = "0" + hexEffLength + content;
                    }
                    else
                    {
                        sms.Msgcontent = hexEffLength + content;
                    }

                    ///// MsgContent

                    //// CRC16

                    //// Generate CRC16 and convert to 16进制
                    //string crcHex = crc16.GetChecksumHex(Encoding.Default.GetBytes(sms.Msgcontent));

                    sms.Msglen = sms.Msgcontent.Length;

                    Monitor_DB.instance.db.SMS_Send.InsertOnSubmit(sms);
                    Monitor_DB.instance.db.SubmitChanges(ConflictMode.FailOnFirstConflict);

                    // 5组卡号发一次
                    i = i + 5;
                }

                return true;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }

        // 04：删除卡号
        public bool DeleteDoor_AuthCard(string deviceId, string MonitorDev_Id)
        {
            try
            {
                string mobileNumOri = getMobileNum(MonitorDev_Id);

                if (mobileNumOri.Length != 11)
                {
                    MessageBox.Show("手机号不正确！号码：%s", mobileNumOri.Length.ToString());
                    return false;
                }

                // Add "86" for sms
                string mobileNum = "86" + mobileNumOri;


                SMS_Send sms = new SMS_Send();
                sms.DestID = mobileNum;
                sms.Disposed = 0;
                sms.DisposedTime = null;
                sms.InsertTime = DateTime.Now;
                sms.Acked = 0;

                string Device_ID = getMonitorDeviceId(MonitorDev_Id);
                sms.Device_ID = Device_ID;
                sms.Command = "04";

                ///// MsgContent

                // Time
                string time = getDateTime();

                string content = Device_ID + "04" + time;

                // MsgContent
                string hexEffLength = Convert.ToString(content.Length, 16).ToUpper();
                if (hexEffLength.Length < 2)
                {

                    sms.Msgcontent = "0" + hexEffLength + content;
                }
                else
                {
                    sms.Msgcontent = hexEffLength + content;
                }

                ///// MsgContent


                //// CRC16

                //// Generate CRC16 and convert to 16进制
                //string crcHex = crc16.GetChecksumHex(Encoding.Default.GetBytes(sms.Msgcontent));
     
                sms.Msglen = sms.Msgcontent.Length;

                Monitor_DB.instance.db.SMS_Send.InsertOnSubmit(sms);
                Monitor_DB.instance.db.SubmitChanges(ConflictMode.FailOnFirstConflict);

                return true;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }

        // 05：查询卡号
        public bool QueryDoor_AuthCard(string deviceId, string MonitorDev_Id)
        {
            try
            {
                string mobileNumOri = getMobileNum(MonitorDev_Id);

                if (mobileNumOri.Length != 11)
                {
                    MessageBox.Show("手机号不正确！号码：%s", mobileNumOri.Length.ToString());
                    return false;
                }

                // Add "86" for sms
                string mobileNum = "86" + mobileNumOri;


                SMS_Send sms = new SMS_Send();
                sms.DestID = mobileNum;
                sms.Disposed = 0;
                sms.DisposedTime = null;
                sms.InsertTime = DateTime.Now;
                sms.Acked = 0;

                string Device_ID = getMonitorDeviceId(MonitorDev_Id);
                sms.Device_ID = Device_ID;
                sms.Command = "05";

                ///// MsgContent

                // Time
                string time = getDateTime();

                string content = Device_ID + "05" + time;

                // MsgContent
                string hexEffLength = Convert.ToString(content.Length, 16).ToUpper();
                if (hexEffLength.Length < 2)
                {

                    sms.Msgcontent = "0" + hexEffLength + content;
                }
                else
                {
                    sms.Msgcontent = hexEffLength + content;
                }

                ///// MsgContent

                //// CRC16

                //// Generate CRC16 and convert to 16进制
                //string crcHex = crc16.GetChecksumHex(Encoding.Default.GetBytes(sms.Msgcontent));

                sms.Msglen = sms.Msgcontent.Length;

                Monitor_DB.instance.db.SMS_Send.InsertOnSubmit(sms);
                Monitor_DB.instance.db.SubmitChanges(ConflictMode.FailOnFirstConflict);

                return true;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }

        // 06：指定设备号
        public bool SendDeviceId(string deviceId, string MonitorDev_Id)
        {
            try
            {
                string mobileNumOri = getMobileNum(MonitorDev_Id);

                if (mobileNumOri.Length != 11)
                {
                    MessageBox.Show("手机号不正确！号码：%s", mobileNumOri.Length.ToString());
                    return false;
                }

                // Add "86" for sms
                string mobileNum = "86" + mobileNumOri;


                SMS_Send sms = new SMS_Send();
                sms.DestID = mobileNum;
                sms.Disposed = 0;
                sms.DisposedTime = null;
                sms.InsertTime = DateTime.Now;
                sms.Acked = 0;

                string Device_ID = getMonitorDeviceId(MonitorDev_Id);
                sms.Device_ID = Device_ID;
                sms.Command = "06";

                ///// MsgContent

                // Time
                string time = getDateTime();

                string content = Device_ID + "06" + time;

                // MsgContent
                string hexEffLength = Convert.ToString(content.Length, 16).ToUpper();
                if (hexEffLength.Length < 2)
                {

                    sms.Msgcontent = "0" + hexEffLength + content;
                }
                else
                {
                    sms.Msgcontent = hexEffLength + content;
                }

                ///// MsgContent

                //// CRC16

                //// Generate CRC16 and convert to 16进制
                //string crcHex = crc16.GetChecksumHex(Encoding.Default.GetBytes(sms.Msgcontent));
  
                sms.Msglen = sms.Msgcontent.Length;

                Monitor_DB.instance.db.SMS_Send.InsertOnSubmit(sms);
                Monitor_DB.instance.db.SubmitChanges(ConflictMode.FailOnFirstConflict);

                return true;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }

        // 07: 复位设备
        public bool ResetDevice(string deviceId, string MonitorDev_Id)
        {
            try
            {
                string mobileNumOri = getMobileNum(MonitorDev_Id);

                if (mobileNumOri.Length != 11)
                {
                    MessageBox.Show("手机号不正确！号码：%s", mobileNumOri.Length.ToString());
                    return false;
                }

                // Add "86" for sms
                string mobileNum = "86" + mobileNumOri;


                SMS_Send sms = new SMS_Send();
                sms.DestID = mobileNum;
                sms.Disposed = 0;
                sms.DisposedTime = null;
                sms.InsertTime = DateTime.Now;
                sms.Acked = 0;

                string Device_ID = getMonitorDeviceId(MonitorDev_Id);
                sms.Device_ID = Device_ID;
                sms.Command = "07";

                ///// MsgContent

                // Time
                string time = getDateTime();

                string content = Device_ID + "07" + time;

                // MsgContent
                string hexEffLength = Convert.ToString(content.Length, 16).ToUpper();
                if (hexEffLength.Length < 2)
                {

                    sms.Msgcontent = "0" + hexEffLength + content;
                }
                else
                {
                    sms.Msgcontent = hexEffLength + content;
                }

                ///// MsgContent

                //// CRC16

                //// Generate CRC16 and convert to 16进制
                //string crcHex = crc16.GetChecksumHex(Encoding.Default.GetBytes(sms.Msgcontent));

                sms.Msglen = sms.Msgcontent.Length;

                Monitor_DB.instance.db.SMS_Send.InsertOnSubmit(sms);
                Monitor_DB.instance.db.SubmitChanges(ConflictMode.FailOnFirstConflict);

                return true;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        // 08: 指定设备IP地址端口号
        public bool SetDeiviceIP_Port(string deviceId, string MonitorDev_Id, string s_IP)
        {
            try
            {
                string mobileNum = getMobileNum(MonitorDev_Id);

                if (mobileNum.Length != 11)
                {
                    MessageBox.Show("手机号不正确！号码：%s", mobileNum.Length.ToString());
                    return false;
                }

                // Add "86" for sms
                mobileNum = "86" + mobileNum;

                SMS_Send sms = new SMS_Send();
                sms.DestID = mobileNum;
                sms.Disposed = 0;
                sms.DisposedTime = null;
                sms.InsertTime = DateTime.Now;
                sms.Acked = 0;

                string Device_ID = getMonitorDeviceId(MonitorDev_Id);
                sms.Device_ID = Device_ID;
                sms.Command = "08";

                ///// MsgContent

                // Time
                string time = getDateTime();

                string content = Device_ID + "08" + s_IP + time;

                // MsgContent
                string hexEffLength = Convert.ToString(content.Length, 16).ToUpper();
                if (hexEffLength.Length < 2)
                {

                    sms.Msgcontent = "0" + hexEffLength + content;
                }
                else
                {
                    sms.Msgcontent = hexEffLength + content;
                }

                ///// MsgContent


                //// CRC16

                //// Generate CRC16 and convert to 16进制
                //string crcHex = crc16.GetChecksumHex(Encoding.Default.GetBytes(sms.Msgcontent));

                sms.Msglen = sms.Msgcontent.Length;

                Monitor_DB.instance.db.SMS_Send.InsertOnSubmit(sms);
                Monitor_DB.instance.db.SubmitChanges(ConflictMode.FailOnFirstConflict);

                return true;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        // 09: 指定设备手机号
        public bool SetDeivicePhoneNum(string MonitorDev_Id, string PhoneNum)
        {
            try
            {
                string mobileNumOri = getMobileNum(MonitorDev_Id);

                if (mobileNumOri.Length != 11)
                {
                    MessageBox.Show("手机号不正确！号码：%s", mobileNumOri.Length.ToString());
                    return false;
                }

                // Add "86" for sms
                string mobileNum = "86" + mobileNumOri;

                SMS_Send sms = new SMS_Send();
                sms.DestID = mobileNum;
                sms.Disposed = 0;
                sms.DisposedTime = null;
                sms.InsertTime = DateTime.Now;
                sms.Acked = 0;

                string Device_ID = getMonitorDeviceId(MonitorDev_Id);
                sms.Device_ID = Device_ID;
                sms.Command = "09";

                ///// MsgContent

                // Time
                string time = getDateTime();

                // Content的手机号后补一位数0，使为偶数,方便硬件计算CRC
                string content = Device_ID + "09" + PhoneNum + "0" + time;

                // MsgContent
                string hexEffLength = Convert.ToString(content.Length, 16).ToUpper();
                if (hexEffLength.Length < 2)
                {

                    sms.Msgcontent = "0" + hexEffLength + content;
                }
                else
                {
                    sms.Msgcontent = hexEffLength + content;
                }

                ///// MsgContent


                //// CRC16

                //// Generate CRC16 and convert to 16进制
                //string crcHex = crc16.GetChecksumHex(Encoding.Default.GetBytes(sms.Msgcontent));

                sms.Msglen = sms.Msgcontent.Length;

                Monitor_DB.instance.db.SMS_Send.InsertOnSubmit(sms);
                Monitor_DB.instance.db.SubmitChanges(ConflictMode.FailOnFirstConflict);

                return true;
            }
            catch (Exception Ex)
            {
                MessageBox.Show(Ex.Message, "错误！", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
    }
}
